 package com.glory.dgcpcpda.base;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;

import com.glory.dgcpcpda.activity.LoginActivity;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_InitUtils;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

 /**
 * FileName: MyApp
 * Author: XJH
 * Date: 2020/5/12 11:30
 * Description:
 * History:
 */
public class MyApp extends Application {

    public static Context app;
    private static MyApp instance;
    private long TINE_TASK_AN_HOUR = 60 * 60 * 1000L;
    private int code;
    private static final String TAG = "GLORY_TIMER_TASK";

     private final Timer timer = new Timer();
     private TimerTask task;
     Handler handler = new Handler(){
         @Override
         public void handleMessage(@NonNull Message msg) {
             if (msg.what == 5486){
                 Log.e(TAG, FreeApi_DateUtils.getNowStringDate("HH:mm:ss") +" 收到定时任务" );
                 //比对版本
                 detectionUpdate();
             }
             super.handleMessage(msg);
         }
     };

    public static MyApp getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        app = getApplicationContext();
        FreeUI_InitUtils.init(getApplicationContext(), this, true,180 * 1000L,0);
        FreeUI_InitUtils.setTheme(FreeApi_StaticMembers.THEME_GLORY);
        Log.e(TAG, FreeApi_DateUtils.getNowStringDate("HH:mm:ss") + "APP启动了");

        new Handler().postDelayed(() -> showTimer(),TINE_TASK_AN_HOUR);
    }


     private void showTimer() {
         Log.e(TAG,  FreeApi_DateUtils.getNowStringDate("HH:mm:ss") + "开始执行定时任务");
         task = new TimerTask() {
             @Override
             public void run() {
                 Message message = new Message();
                 message.what = 5486;
                 Log.e(TAG, FreeApi_DateUtils.getNowStringDate("HH:mm:ss") +" 发送定时任务" );
                 handler.sendMessage(message);
             }
         };
         timer.schedule(task,new Date(),TINE_TASK_AN_HOUR);
     }

     @Override
     public void onTerminate() {
         //关闭定时任务
         task.cancel();
         Log.e(TAG, "onTerminate: 关闭定时任务" );
         super.onTerminate();
     }

     private void detectionUpdate()    {
         PackageManager manager = getPackageManager();
         PackageInfo info = null;
         try {
             info = manager.getPackageInfo(getPackageName(), 0);
         } catch (PackageManager.NameNotFoundException e) {
             e.printStackTrace();
         }
         String version = info.versionName;
         FreeUI_EntityCallBack<FreeUI_VersionEntity> callBack = new FreeUI_EntityCallBack<FreeUI_VersionEntity>
                 (new TypeToken<FreeUI_VersionEntity>() {
                 }.getType()) {

             @Override
             public void onSuccess(Response<FreeUI_VersionEntity> response) {
                 FreeUI_VersionEntity entity = response.body();
                 entity.setCurrentVersion(version);
                 code = compareVersion(version,entity.getVersion());
                 if(code == -1) {
                     Toast.makeText(MyApp.this, "发现最新版本!正在前往更新", Toast.LENGTH_SHORT).show();
                     timer.cancel();
//
//                     Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//                     PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 200, intent, PendingIntent.FLAG_ONE_SHOT);
//                     AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//                     mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000L, restartIntent);

//                     FreeApi_ActivityManager.getActivityManager().AppExit(getApplicationContext());
                     FreeApi_ActivityManager.getActivityManager().finishAllActivity();
                     Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
                     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                     intent.setAction(intent.FLAG_ACTIVITY_NEW_TASK);
                     startActivity(intent);

                 }

             }

             @Override
             public void onError
                     (Response<FreeUI_VersionEntity> response) {
                 super.onError(response);
             }
         };
         Map<String, String> map = new HashMap<>();
         FreeApi_NetUtils.requestGetNet(Constant.FILE_URL, this, map, callBack);
     }

     public static int compareVersion(String version1, String version2) {
         if (version1.equals(version2)) {
             return 0;
         } else {
             String[] version1Array = version1.split("\\.");
             String[] version2Array = version2.split("\\.");
             Log.d("HomePageActivity", "version1Array==" + version1Array.length);
             Log.d("HomePageActivity", "version2Array==" + version2Array.length);
             int index = 0;
             int minLen = Math.min(version1Array.length, version2Array.length);
             int diff = 0;
             Log.d("HomePageActivity", "verTag2=2222=" + version1Array[index]);

             while(index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
                 ++index;
             }

             if (diff == 0) {
                 int i;
                 for(i = index; i < version1Array.length; ++i) {
                     if (Integer.parseInt(version1Array[i]) > 0) {
                         return 1;
                     }
                 }

                 for(i = index; i < version2Array.length; ++i) {
                     if (Integer.parseInt(version2Array[i]) > 0) {
                         return -1;
                     }
                 }

                 return 0;
             } else {
                 return diff > 0 ? 1 : -1;
             }
         }
     }
}
